'use client';

import React, { useState, useEffect } from 'react';
import { Button, Input, Select, Pagination, Card, Tag, Space } from 'antd';
import { SearchOutlined, PlusOutlined } from '@ant-design/icons';
import { useRouter } from 'next/navigation';
import { request } from '@/utils/request';
import { ResponseUtil } from '@/utils/response';
import qs from 'qs';
import TaskItem from './components/TaskItem';

const { Option } = Select;

interface TaskCategory {
  id: number;
  name: string;
  imageUrl: string;
  description: string;
}

interface Task {
  id: number;
  title: string;
  content: string;
  status: string;
  points: number;
  viewCount: number;
  createdAt: string;
  category: TaskCategory;
  author: {
    id: number;
    nickname: string;
    avatar: string;
  };
  applications: Array<{
    id: number;
    applicant: {
      id: number;
      nickname: string;
    };
  }>;
}

const TaskPage: React.FC = () => {
  const router = useRouter();
  const [tasks, setTasks] = useState<Task[]>([]);
  const [loading, setLoading] = useState(false);
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [total, setTotal] = useState(0);
  const [searchKeyword, setSearchKeyword] = useState('');
  const [selectedCategory, setSelectedCategory] = useState<number | null>(null);
  const [selectedStatus, setSelectedStatus] = useState<string | null>('APPROVED'); // 默认选中发布中任务
  const [sortBy, setSortBy] = useState('createdAt');
  const [sortOrder, setSortOrder] = useState<'asc' | 'desc'>('desc');
  const [categories, setCategories] = useState<TaskCategory[]>([]);

  // 获取任务分类
  const fetchCategories = async () => {
    try {
      const response = await request('/tasks/categories',{
        method:"GET"
      });
      if (ResponseUtil.success(response)) {
        setCategories(response.data as TaskCategory[]);
      }
    } catch (error) {
      console.error('获取任务分类失败:', error);
    }
  };

  // 获取任务列表
  const fetchTasks = async () => {
    setLoading(true);
    try {
      const params = {
        page: currentPage,
        pageSize,
        keyword: searchKeyword,
        categoryId: selectedCategory,
        status: selectedStatus, // 新增状态筛选参数
        sortBy,
        sortOrder,
      };
      
      const queryStr = qs.stringify(params, { skipNulls: true });
      console.log(queryStr, 'queryStr');
      const response = await request(`/tasks?${queryStr}`, {
        method: 'GET',
      });
      if (ResponseUtil.success(response)) {
        setTasks((response.data as {list:Task[],total:number}).list);
        setTotal((response.data as {list:Task[],total:number}).total);
      }
    } catch (error) {
      console.error('获取任务列表失败:', error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchCategories();
  }, []);

  useEffect(() => {
    fetchTasks();
  }, [currentPage, pageSize, selectedCategory, selectedStatus, sortBy, sortOrder]);

  // 处理搜索
  const handleSearch = (value: string) => {
    setSearchKeyword(value);
    setCurrentPage(1);
    // 立即执行搜索，获取搜索结果
    setTimeout(() => {
      fetchTasks();
    }, 0);
  };

  // 处理分类筛选
  const handleCategoryChange = (value: number | null) => {
    setSelectedCategory(value);
    setCurrentPage(1);
    // 移除立即刷新，让useEffect处理
  };

  // 处理状态筛选
  const handleStatusChange = (value: string | null) => {
    // 如果选择"全部"，则传递'all'，否则传递具体状态值
    const statusValue = value === null ? 'all' : value;
    setSelectedStatus(statusValue);
    setCurrentPage(1);
    // 移除立即刷新，让useEffect处理
  };

  // 处理排序
  const handleSortChange = (key: string) => {
    const [field, order] = key.split('-');
    setSortBy(field);
    setSortOrder(order as 'asc' | 'desc');
    setCurrentPage(1);
  };

  // 排序选项
  const sortOptions = [
    { key: 'createdAt-desc', label: '最新发布', field: 'createdAt', order: 'desc' },
    { key: 'createdAt-asc', label: '最早发布', field: 'createdAt', order: 'asc' },
    { key: 'points-desc', label: '积分最高', field: 'points', order: 'desc' },
    { key: 'points-asc', label: '积分最低', field: 'points', order: 'asc' },
    { key: 'viewCount-desc', label: '浏览最多', field: 'viewCount', order: 'desc' },
    { key: 'viewCount-asc', label: '浏览最少', field: 'viewCount', order: 'asc' },
  ];

  // 获取当前排序的显示文本
  const getCurrentSortLabel = () => {
    const currentSort = `${sortBy}-${sortOrder}`;
    const option = sortOptions.find(opt => opt.key === currentSort);
    return option ? option.label : '排序';
  };



  return (
    <div className="min-h-screen bg-gray-50">
      <div className="max-w-7xl mx-auto px-4 py-8">
        {/* 页面标题 */}
        <div className="mb-8">
          <h1 className="text-3xl font-normal text-gray-900 mb-2">任务大厅</h1>
          <p className="text-gray-600">发布任务、接单赚钱，让技能变现</p>
        </div>

        {/* 筛选和操作栏 */}
        <div className="bg-white rounded-lg p-6 mb-6 shadow-sm space-y-4">
          {/* 第一排：搜索和发布任务 */}
          <div className="flex items-center gap-4">
            <div className="flex-1 min-w-64">
              <Input
                placeholder="搜索任务标题或内容"
                prefix={<SearchOutlined />}
                value={searchKeyword}
                onChange={(e) => setSearchKeyword(e.target.value)}
                onPressEnter={(e) => handleSearch((e.target as HTMLInputElement).value)}
                allowClear
                onClear={() => handleSearch('')}
              />
            </div>
            <Button 
              type="primary" 
              icon={<SearchOutlined />}
              onClick={() => handleSearch(searchKeyword)}
           
            >
              搜索
            </Button>
            <Button 
              type="primary" 
              icon={<PlusOutlined />}
              onClick={() => router.push('/tasks/publish')}
        
            >
              发布任务
            </Button>
          </div>

          {/* 第二排：任务分类 */}
          <div className="flex items-center gap-2">
            <span className="text-sm text-gray-600">任务分类:</span>
            <div className="flex items-center gap-2">
              <button
                onClick={() => handleCategoryChange(null)}
                className={`px-3 py-1 text-sm rounded-full transition-colors ${
                  selectedCategory === null
                    ? 'bg-cyan-500 text-white'
                    : 'bg-gray-100 text-gray-600 hover:bg-gray-200'
                }`}
              >
                全部
              </button>
              {categories.map(category => (
                <button
                  key={category.id}
                  onClick={() => handleCategoryChange(category.id)}
                  className={`px-3 py-1 text-sm rounded-full transition-colors ${
                    selectedCategory === category.id
                      ? 'bg-cyan-500 text-white'
                      : 'bg-gray-100 text-gray-600 hover:bg-gray-200'
                  }`}
                >
                  {category.name}
                </button>
              ))}
            </div>
          </div>

          {/* 第三排：任务状态 */}
          <div className="flex items-center gap-2">
            <span className="text-sm text-gray-600">任务状态:</span>
            <div className="flex items-center gap-2">
              <button
                onClick={() => handleStatusChange(null)}
                className={`px-3 py-1 text-sm rounded-full transition-colors ${
                  selectedStatus === null || selectedStatus === 'all'
                    ? 'bg-cyan-500 text-white'
                    : 'bg-gray-100 text-gray-600 hover:bg-gray-200'
                }`}
              >
                全部
              </button>
              <button
                onClick={() => handleStatusChange('APPROVED')}
                className={`px-3 py-1 text-sm rounded-full transition-colors ${
                  selectedStatus === 'APPROVED'
                    ? 'bg-cyan-500 text-white'
                    : 'bg-gray-100 text-gray-600 hover:bg-gray-200'
                }`}
              >
                发布中任务
              </button>
              <button
                onClick={() => handleStatusChange('IN_PROGRESS')}
                className={`px-3 py-1 text-sm rounded-full transition-colors ${
                  selectedStatus === 'IN_PROGRESS'
                    ? 'bg-cyan-500 text-white'
                    : 'bg-gray-100 text-gray-600 hover:bg-gray-200'
                }`}
              >
                执行中任务
              </button>

            </div>
          </div>

          {/* 第四排：排序 */}
          <div className="flex items-center gap-2">
            <span className="text-sm text-gray-600">排序:</span>
            <div className="flex items-center gap-2">
              {sortOptions.map(option => {
                const isActive = sortBy === option.field && sortOrder === option.order;
                return (
                  <button
                    key={option.key}
                    onClick={() => handleSortChange(option.key)}
                    className={`px-3 py-1 text-sm rounded-full transition-colors ${
                      isActive
                        ? 'bg-cyan-500 text-white'
                        : 'bg-gray-100 text-gray-600 hover:bg-gray-200'
                    }`}
                  >
                    {option.label}
                  </button>
                );
              })}
            </div>
          </div>
        </div>

        {/* 任务列表 */}
        <div className="bg-white rounded-lg shadow-sm">
          {loading ? (
            // 加载状态 - 显示骨架屏
            <div className="space-y-4 p-6">
              {[...Array(6)].map((_, index) => (
                <div key={index} className="animate-pulse">
                  <div className="flex items-start space-x-4">
                    <div className="flex-1 space-y-3">
                      <div className="flex space-x-2">
                        <div className="h-5 bg-gray-200 rounded w-16"></div>
                        <div className="h-5 bg-gray-200 rounded w-20"></div>
                      </div>
                      <div className="h-5 bg-gray-200 rounded w-3/4"></div>
                      <div className="h-4 bg-gray-200 rounded w-full"></div>
                      <div className="flex space-x-6">
                        <div className="h-4 bg-gray-200 rounded w-20"></div>
                        <div className="h-4 bg-gray-200 rounded w-24"></div>
                        <div className="h-4 bg-gray-200 rounded w-16"></div>
                      </div>
                    </div>
                    <div className="flex-shrink-0">
                      <div className="h-6 bg-gray-200 rounded w-12 mb-1"></div>
                      <div className="h-3 bg-gray-200 rounded w-8"></div>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          ) : (
            // 正常任务列表
            <>
              {tasks.map(task => (
                <TaskItem key={task.id} task={task} />
              ))}
            </>
          )}
        </div>

        {/* 空状态 */}
        {!loading && tasks.length === 0 && (
          <div className="bg-white rounded-lg shadow-sm p-6">
            <div className="text-center py-12">
              <div className="mb-4">
                <svg
                  className="mx-auto h-24 w-24 text-gray-300"
                  fill="none"
                  viewBox="0 0 24 24"
                  stroke="currentColor"
                  aria-hidden="true"
                >
                  <path
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    strokeWidth={1.5}
                    d="M9 5H7a2 2 0 00-2 2v10a2 2 0 002 2h8a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-3 7h3m-3 4h3m-6-4h.01M9 16h.01"
                  />
                </svg>
              </div>
              <div className="text-gray-400 text-lg mb-2">暂无任务</div>
              <p className="text-gray-500">试试调整筛选条件或发布新任务</p>
            </div>
          </div>
        )}

        {/* 分页 */}
        {total > 0 && (
          <div className="flex justify-center mt-8">
            <Pagination
              current={currentPage}
              total={total}
              pageSize={pageSize}
              showSizeChanger
              showQuickJumper
              showTotal={(total, range) => `第 ${range[0]}-${range[1]} 条，共 ${total} 条`}
              onChange={(page, size) => {
                setCurrentPage(page);
                setPageSize(size);
              }}
            />
          </div>
        )}
      </div>
    </div>
  );
};

export default TaskPage; 